<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2022/3/17
 * Time: 16:50
 */

namespace app\api\controller;


use pay\Ali;
use pay\Wxservicer;
use think\Db;

class Bomy extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }

    /**
     * 用户积分/佣金信息
     * @return \think\response\Json
     */
    public function userBalanceInfo(){
        $field = 'user_recharge_balance, user_bo_balance, user_bo_fy_balance';
        $user = $this->userInfo($this->user_id, $field);
        $user['canUse'] = $user['user_bo_fy_balance'] - $this->thisMonthFy();
        $user['canUse'] = $user['canUse'] <= 0 ? 0 : $user['canUse'];
        return json(['status' => 200, 'msg' => $user]);
    }
    
    /**
     * 脖脸皮积分明细
     * @return \think\response\Json
     * infoType       积分类型   0 全部   1 收入   2 支出
     * balance_type   1 脖脸皮商品积分   2 特惠商品积分
     * page           页码
     */
    public function balanceList(){
        $infoType = input('infoType'); // 积分明细  0 全部  1 收入  2 支出
        $balance_type = input('balance_type') ? input('balance_type') : 1;

        if($balance_type == 1){
            $where['binte_user_id'] = $this->user_id;
            $where['binte_status'] = 1;
            if($infoType != 0) $where['binte_type'] = $infoType;
            $data = Db::table('up_bo_integral')
                ->where($where)
                ->field('binte_number, binte_type, binte_desc, binte_price, binte_time')
                ->order('binte_time desc')
                ->page($this->page, 10)
                ->select();
        }else{
            $where['inte_user_id'] = $this->user_id;
            if($infoType != 0) $where['inte_type'] = $infoType;
            $data = Db::table('up_integral')
                ->where($where)
                ->field('inte_num, inte_type, inte_des, inte_number, inte_time')
                ->order('inte_time desc')
                ->page($this->page, 10)
                ->select();
        }
        if($data){
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 脖脸皮分佣提现信息展示
     * @return \think\response\Json
     */
    public function withdrawShow(){
        $field = 'user_bo_fy_balance, user_real_name, user_phone, user_shop_name, user_bank_username, 
        user_bank_name, user_bankcard_code, user_code';
        $user = $this->userInfo($this->user_id, $field);
        // 当月的分佣
        $untixian = $this->thisMonthFy();
        // 可提现的分佣，总分佣-当月的分佣
        if($user['user_bo_fy_balance'] < $untixian){
            $user['untixian'] = $user['user_bo_fy_balance'];
        }else{
            $user['untixian'] = $untixian;
        }
        $can_tixian = $user['user_bo_fy_balance'] - $untixian;
        $user['can_tixian'] = $can_tixian <= 0 ? 0 : $can_tixian;
        // 提现规则
        $txRule = Db::table('up_about')->where('id', 8)->value('content');
        return json(['status' => 200, 'msg' => $user, 'rule' => $txRule]);
    }

    /**
     * 脖脸皮佣金明细
     * @return \think\response\Json
     * fy_type       佣金类型   0 全部   1 收入   2 支出
     * page           页码
     */
    public function myBoFy(){
        $fy_type = input('fy_type'); // 佣金明细  0 全部  1 收入  2 支出
        // 明细
        $where = ['binte_user_id' => $this->user_id, 'binte_status' => 1];
        if($fy_type != 0){
            $where['binte_type'] = $fy_type;
        }
        $info = Db::table('up_bo_fy')
            ->join('up_bo_withdraw', 'bw_binte_id = binte_id', 'LEFT')
            ->where($where)
            ->field('binte_id, binte_desc, binte_type, binte_price, binte_time, bw_status, 
            bw_refuse_reason, binte_cate, bw_type, bw_id')
            ->order('binte_time desc')
            ->page($this->page, 10)
            ->select();
        if($info){
            foreach($info as $k => $v){
                if($v['binte_cate'] == 2 && $v['bw_type'] == 1){
                    $withdraw_info = Db::table('up_bo_withdraw_to_integral')
                        ->where(['bwi_binte_id' => $v['binte_id'], 'bwi_bw_id' => $v['bw_id']])
                        ->field('bwi_price, bwi_time')
                        ->order('bwi_time desc')
                        ->select();
                    if($withdraw_info){
                        $info[$k]['withdraw_info'] = $withdraw_info;
                    }else{
                        $info[$k]['withdraw_info'] = [];
                    }
                }else{
                    $info[$k]['withdraw_info'] = [];
                }
            }
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 脖脸皮分佣提现
     * @return \think\response\Json
     * withdraw_price      提现金额
     * withdraw_type       提现方式    1 提现到银行卡   2 提现到积分
     */
    public function doWithdraw(){
        $withdraw_price = input('withdraw_price'); // 提现金额
        $withdraw_type = input('withdraw_type'); // 1 提现到银行卡   2 转到积分

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        // 是否在可提现日期内
        if($withdraw_type == 1){
            $canTx = $this->canTxDate();
            if($canTx['can'] == 2){
                return json(['status' => 0, 'msg' => '每月' . $canTx['date'] . '日可提现']);
            }
        }

        // 个人信息
        $field = 'user_code, user_bo_fy_balance, user_teamer_status, user_agency_sheng_status, user_agency_shi_status, user_agency_qu_status';
        $user = $this->userInfo($this->user_id, $field);
        if(!$user['user_code']) return json(['status' => 0, 'msg' => '请先完善个人信息']);
        if($user['user_teamer_status'] == 2 || $user['user_agency_sheng_status'] == 2 || $user['user_agency_shi_status'] == 2 || $user['user_agency_qu_status'] == 2){
            return json(['status' => 0, 'msg' => '团队长或代理身份冻结，请联系管理员']);
        }

        // 当月的分佣
        $untixian = $this->thisMonthFy();
        // 可提现的分佣，总分佣-当月的分佣
        $can_tixian = $user['user_bo_fy_balance'] - $untixian;
        if($withdraw_price > $can_tixian) return json(['status' => 0, 'msg' => '可提现分佣值不足']);
        
        $withdraw_number = 'BW_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        Db::startTrans();
        try{
            // 更新用户积分
            Db::table('up_u_user')->where('user_id', $this->user_id)->dec('user_bo_fy_balance', $withdraw_price)->update();
            
            // 插入积分明细
            if($withdraw_type == 1){
                $desc = '佣金提现到银行卡';
                $binte_cate = 2;
            }else{
                $desc = '佣金提现转货款';
                $binte_cate = 3;
            }
            $inte_id = $this->insertBoFy($this->user_id, 0, $this->user_id, 0, 2, $desc, $binte_cate, $withdraw_price, $user['user_bo_fy_balance'], 0, 2, 0);

            // 插入提现
            Db::table('up_bo_withdraw')
                ->insert([
                    'bw_user_id' => $this->user_id,
                    'bw_type' => $withdraw_type,
                    'bw_number' => $withdraw_number,
                    'bw_price' => $withdraw_price,
                    'bw_binte_id' => $inte_id,
                    'bw_time' => $this->create_time
                ]);
                
            Db::commit();
            return json(['status' => 200, 'msg' => '提交成功，请耐心等待']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 脖脸皮分佣提现到银行卡部分转货款---暂时不用
     * @return \think\response\Json
     * bw_id     提现ID
     * bwi_price     转积分数量
     */
    public function withdrawToBalance(){
        $bw_id = input('bw_id');
        $bwi_price = input('bwi_price');
        
        if(!$bwi_price) return json(['status' => 0, 'msg' => '请输入金额']);
        $withdraw = Db::table('up_bo_withdraw')->where('bw_id', $bw_id)
            ->field('bw_price, bw_user_id, bw_binte_id')->find();
        $already_zhuan = Db::table('up_bo_withdraw_to_integral')->where('bwi_bw_id', $bw_id)->sum('bwi_price');
        $can_zhuan = $withdraw['bw_price'] - $already_zhuan;
        if($bwi_price > $can_zhuan) return json(['status' => 0, 'msg' => '超出可转积分']);
    
        $user = Db::table('up_u_user')->where('user_id', $withdraw['bw_user_id'])
            ->field('user_bo_balance, user_bo_total_balance')
            ->find();
    
        Db::startTrans();
        try{
            // 更新用户积分
            Db::table('up_u_user')
                ->update([
                    'user_id' => $withdraw['bw_user_id'],
                    'user_bo_balance' => $user['user_bo_balance'] + $bwi_price,
                    'user_bo_total_balance' => $user['user_bo_total_balance'] + $bwi_price
                ]);
        
            // 插入转积分明细
            Db::table('up_bo_withdraw_to_integral')
                ->insert([
                    'bwi_binte_id' => $withdraw['bw_binte_id'],
                    'bwi_bw_id' => $bw_id,
                    'bwi_price' => $bwi_price,
                    'bwi_user_id' => $withdraw['bw_user_id'],
                    'bwi_time' => date('Y-m-d H:i:s')
                ]);
        
            // 插入积分明细
            insertBoInte($withdraw['bw_user_id'], 0, 1, '提现转银行卡-部分转货款', $bwi_price, $user['user_bo_balance'], 0, 4, 9);
        
            Db::commit();
            return json(['code' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code' => 100, 'msg' => $e->getMessage()]);
        }
    }
    
    //***********************************************  脖脸皮订单相关
    
    /**
     * 脖脸皮商品订单列表
     * @return \think\response\Json
     * page         页码
     * order_status 0 全部  1 待支付  2 待发货  3 待收货  4 已完成
     */
    public function boOrderList(){
        $order_status = input('order_status'); // 0 全部  1 待支付  2 待发货  3 待收货  4 已完成
        
        $list = $this->goodsOrder(2, $order_status);
        if($list){
            foreach($list as $k => $v){
                $goods = $this->orderGoodsList($v['bo_id']);
                $list[$k]['goods'] = $goods;
            }
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 脖脸皮订单详情
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $detail = Db::table('up_bo_order')
            ->join('up_user_address', 'bo_addr_id = addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->where('bo_id', $order_id)
            ->field('bo_id, addr_user_name, addr_user_phone, concat(u1.district, u2.district, u3.district, addr_address) address, 
            bo_total_price, bo_status, bo_remark, bo_number, bo_create_time, bo_pay_time, bo_send_time, 
            bo_over_time, bo_close_time, bo_cancel_time, bo_cancel_reason')
            ->find();
        $goods = $this->orderGoodsList($order_id);
        $detail['goods'] = $goods;
        return json(['status' => 200, 'msg' => $detail]);
    }
    
    /**
     * 修改脖脸皮订单收货地址
     * @return \think\response\Json
     * order_id       订单ID
     * addr_id        地址ID
     */
    public function updateAddr(){
        $order_id = input('order_id');
        $addr_id = input('addr_id');
        
        $order = Db::table('up_bo_order')->where('bo_id', $order_id)->field('bo_status, bo_addr_id')->find();
        if($order['bo_status'] != 1 && $order['bo_status'] != 2) return json(['status' => 0, 'msg' => '该订单暂不支持修改收货地址']);
        if($order['bo_addr_id'] == $addr_id) return json(['status' => 200, 'msg' => '修改成功']);
        
        $res = Db::table('up_bo_order')->update([
            'bo_id' => $order_id,
            'bo_addr_id' => $addr_id
        ]);
        if($res){
            return json(['status' => 200, 'msg' => '修改成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 取消脖脸皮订单
     * @return \think\response\Json
     * order_id      订单ID
     */
    public function cancelOrder(){
        $order_id = input('order_id');
        
        $order = Db::table('up_bo_order')->where('bo_id', $order_id)->field('bo_status')->find();
        if($order['bo_status'] != 1) return json(['status' => 0, 'msg' => '订单当前状态不支持取消']);
    
        $goods = $this->orderGoodsList($order_id);
        
        Db::startTrans();
        try{
            // 修改订单状态
            Db::table('up_bo_order')->update([
                'bo_id' => $order_id,
                'bo_status' => 6,
                'bo_cancel_time' => $this->create_time,
                'bo_cancel_reason' => '用户主动取消'
            ]);
            
            // 增加库存&减销量
            foreach($goods as $k => $v){
                Db::table('up_bo_goods')
                    ->update([
                        'bg_id' => $v['boi_goods_id'],
                        'bg_stock' => $v['bg_stock'] + $v['boi_goods_number'],
                        'bg_sale_number' => $v['bg_sale_number'] - $v['boi_goods_number']
                    ]);
            }
            
            Db::commit();
            return json(['status' => 200, 'msg' => '取消成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 脖脸皮订单确认收货
     * @return \think\response\Json
     * order_id      订单ID
     */
    public function confirmOrder(){
        $order_id = input('order_id');
        $order = Db::table('up_bo_order')
            ->where('bo_id', $order_id)
            ->field('bo_status, bo_total_price, bo_addr_id')
            ->find();
        if($order['bo_status'] != 3) return json(['status' => 0, 'msg' => '订单状态异常']);

        // 修改订单状态
        $res = Db::table('up_bo_order')
            ->update([
                'bo_id' => $order_id,
                'bo_status' => 4,
                'bo_over_time' => $this->create_time
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 物流信息
     * @return \think\response\Json
     * order_id      订单ID
     */
    public function showWuLiu(){
        $order_id = input('order_id');
        // 订单
        $order = Db::table('up_bo_order')
            ->join('up_user_address', 'addr_id = bo_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('bo_express_company, bo_express_code, bo_addr_id, bo_number, bo_create_time, 
            bo_pay_time, concat(u1.district, u2.district, u3.district, addr_address) address,  
            addr_user_name, addr_user_phone')
            ->where('bo_id', $order_id)
            ->find();

        //*********** 获取快递公司编码
        $code = $order['bo_express_code'];
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
        
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'order' => $order/*, 'address' => $address*/]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'order' => $order/*, 'address' => $address*/]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'order' => $order/*, 'address' => $address*/]);
            }
        }
    }
    
    /**
     * 关闭脖脸皮订单---未支付
     * @return \think\response\Json
     * order_id      订单ID
     */
    public function closeBoOrder(){
        $order_id = input('order_id');
        $order = Db::table('up_bo_order')->where('bo_id', $order_id)->field('bo_status')->find();
        if($order['bo_status'] == 1){
            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_bo_order')->where('bo_id', $order_id)->update([
                    'bo_status' => 5,
                    'bo_close_time' => date('Y-m-d H:i:s')
                ]);
        
                // 释放库存&减销量
                $goods = Db::table('up_bo_order_info')
                    ->join('up_bo_goods', 'boi_goods_id = bg_id', 'LEFT')
                    ->where('boi_order_id', $order_id)
                    ->field('boi_goods_id, boi_goods_number, bg_sale_number, bg_stock')
                    ->select();
                foreach($goods as $k => $v){
                    Db::table('up_bo_goods')->where('bg_id', $v['boi_goods_id'])->update([
                        'bg_stock' => $v['bg_stock'] + $v['boi_goods_number'],
                        'bg_sale_number' => $v['bg_sale_number'] - $v['boi_goods_number']
                    ]);
                }
                Db::commit();
                return json(['status' => 200, 'msg' => true]);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
    }
    
    //*************************************************  礼包订单相关    start   **************************************//
    
    /**
     * 礼包订单列表---购买的礼包
     * @return \think\response\Json
     * bog_status     订单状态  0 全部  1 待支付   2 待发货   3 待收货   4 已完成
     */
    public function giftbagOrderList(){
        $bog_status = input('bog_status');
        
        $order = $this->giftBagOrder(2, 2, $bog_status, $this->user_id);
        if($order){
            return json(['status' => 200, 'msg' => $order]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 修改礼包订单收货地址
     * @return \think\response\Json
     * bog_id      礼包订单ID
     * addr_id     收货地址ID
     */
    public function updateGiftAddr(){
        $bog_id = input('bog_id');
        $addr_id = input('addr_id');
        
        $order = Db::table('up_bo_orderg')->where('bog_id', $bog_id)->field('bog_status, bog_addr_id')->find();
        if($order['bog_status'] != 1 && $order['bog_status'] != 2) return json(['status' => 0, 'msg' => '该订单暂不支持修改收货地址']);
        if($order['bog_addr_id'] == $addr_id) return json(['status' => 200, 'msg' => '修改成功']);
        
        $res = Db::table('up_bo_orderg')
            ->update([
                'bog_id' => $bog_id,
                'bog_addr_id' => $addr_id
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '修改成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 取消礼包订单
     * @return \think\response\Json
     * bog_id      礼包订单ID
     */
    public function cancelGiftOrder(){
        $bog_id = input('bog_id');
        
        $order = Db::table('up_bo_orderg')
            ->where('bog_id', $bog_id)
            ->field('bog_status, bog_gift_id, bog_pay_type, bog_total_price, bog_number, bog_is_pay')
            ->find();
        if($order['bog_status'] != 1){
            return json(['status' => 0, 'msg' => '当前订单状态不支持取消']);
        }

        // 修改订单状态
        $res = Db::table('up_bo_orderg')
            ->update([
                'bog_id' => $bog_id,
                'bog_status' => 6,
                'bog_cancel_time' => $this->create_time,
                'bog_cancel_reason' => '用户主动取消'
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
        
    }
    
    /**
     * 礼包订单物流信息
     * @return \think\response\Json
     * bog_id      礼包订单ID
     */
    public function showGiftWuLiu(){
        $bog_id = input('bog_id');
        $order = Db::table('up_bo_orderg')
            ->join('up_user_address', 'addr_id = bog_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('bog_express_company, bog_express_code, bog_addr_id, bog_number, bog_create_time, 
            bog_pay_time, concat(u1.district, u2.district, u3.district, addr_address) address,  
            addr_user_name, addr_user_phone')
            ->where('bog_id', $bog_id)
            ->find();
    
        //*********** 获取快递公司编码
        $code = $order['bog_express_code'];
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
        
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'order' => $order/*, 'address' => $address*/]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'order' => $order/*, 'address' => $address*/]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'order' => $order/*, 'address' => $address*/]);
            }
        }
    }
    
    /**
     * 确认礼包订单收货
     * @return \think\response\Json
     * bog_id       礼包订单ID
     * bog_get_way     礼包领取方式（快递/XX店铺领取）
     */
    public function confirmGiftOrder(){
        $bog_id = input('bog_id');
        $bog_get_way = input('bog_get_way');
        $order = Db::table('up_bo_orderg')->where('bog_id', $bog_id)->field('bog_user_id, bog_status, bog_gift_id, bog_total_price')->find();
        if($order['bog_status'] != 3) return json(['status' => 0, 'msg' => '订单状态异常']);

        // 修改订单状态
        $res = Db::table('up_bo_orderg')->update([
            'bog_id' => $bog_id,
            'bog_status' => 4,
            'bog_over_time' => $this->create_time,
            'bog_get_way' => $bog_get_way
        ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    /**
     * 礼包订单申请售后
     * @return \think\response\Json
     * order_id            订单ID
     * aftersale_reason    售后原因
     */
    public function afterSale(){
        $order_id = input('order_id');
        $aftersale_reason = input('reason');

        $order = Db::table('up_bo_orderg')
            ->where('bog_id', $order_id)
            ->field('bog_over_time, bog_status')
            ->find();
        if($order['bog_status'] != 4) return json(['status' => 0, 'msg' => '当前订单状态不支持售后']);
        // 确认收货15天后，不允许退货
        $days = date('Y-m-d H:i:s', strtotime('-15 days'));
        if($order['bog_over_time'] < $days) return json(['status' => 0, 'msg' => '超过15天，不可售后']);

        $data = [
            'bog_id' => $order_id,
            'bog_status' => 7,
            'bog_aftersale_status' => 2,
            'bog_aftersale_reason' => $aftersale_reason,
            'bog_aftersale_time' => $this->create_time
        ];
        $res = Db::table('up_bo_orderg')->update($data);
        if($res){
            return json(['status' => 200, 'msg' => '售后申请提交成功，请耐心等待']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 关闭礼包订单---未支付
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function closeGiftbagOrder(){
        $order_id = input('order_id');
        $order = Db::table('up_bo_orderg')->where('bog_id', $order_id)->field('bog_status')->find();
        if($order['bog_status'] == 1){
            $res = // 修改订单状态
                Db::table('up_bo_orderg')->where('bog_id', $order_id)
                    ->update([
                        'bog_status' => 5,
                        'bog_close_time' => date('Y-m-d H:i:s')
                    ]);
            if($res){
                return json(['status' => 200, 'msg' => true]);
            }else{
                return json(['status' => 0, 'msg' => false]);
            }
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
    }

    //*************************************************  礼包订单相关    end   **************************************//


    //**************************************************   赠品相关    start  *********************************//
    
    /**
     * 用于判断用户当前是否可以领取赠品
     * @return \think\response\Json
     * bog_id        礼包ID
     */
    public function canGet(){
        $bog_id = input('bog_id');
        $get_type = input('get_type'); // 1 店铺   2 上级
        $can = $this->canGetZeng($bog_id, $get_type);
        return json($can);
    }

    /**
     * 直接支付页面
     * @return \think\response\Json
     * boz_id      赠品订单ID
     */
    public function orderPayPage(){
        $boz_id = input('boz_id');
        $order = Db::table('up_bo_orderz')
            ->where('boz_id', $boz_id)
            ->field('boz_pay_type, boz_price')
            ->find();
        return json(['status' => 200, 'msg' => $order]);
    }
    
    /**
     * 赠品订单支付----赠品列表
     * @return \think\response\Json
     * boz_id        赠品订单ID
     * pay_type      支付方式    1 积分   2 微信   3 支付宝
     */
    public function payZengOrder(){
        $boz_id = input('boz_id');
        $pay_type = input('pay_type');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $order = Db::table('up_bo_orderz')
            ->join('up_bo_orderg', 'bog_id = boz_order_id', 'LEFT')
            ->where('boz_id', $boz_id)
            ->field('boz_status, boz_price, boz_order_id, boz_user_id, boz_get_month, boz_pay_type, 
            boz_number, boz_no, bog_zeng_number, bog_id, boz_get_type')
            ->find();
        if($order['boz_status'] != 1) return json(['status' => 0, 'msg' => '订单状态异常']);
        if($order['bog_zeng_number'] == 0 || $order['boz_no'] > $order['bog_zeng_number']){
            return json(['status' => 0, 'msg' => '剩余可领数量不足']);
        }

//        $month = date('Y-m');
//        if(strtotime($month) != strtotime($order['boz_get_month'])){
//            Db::table('up_bo_orderz')->where('boz_id', $boz_id)->setField('boz_status', 6);
//            return json(['status' => 0, 'msg' => '该订单领取年月与当前年月不符']);
//        }
        // 判断是否可以领取
        $can = $this->canGetZeng($order['bog_id'], $order['boz_get_type']);
        if($can['status'] != 200) return json($can);

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        $update = [
            'boz_id' => $boz_id,
            'boz_pay_type' => $pay_type,
            'boz_update_time' => $this->create_time
        ];
        $order_number = 'BZ_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);

        Db::startTrans();
        try{
            if($pay_type == 2){
                $update['boz_number'] = $order_number;
                // 调起微信支付
                $wxConfig = config('wechat_servicer');
                $wxConfig['sub_mchid'] = $mchid['mch_code'];
                $wx = new Wxservicer($wxConfig);
                $return = $wx->WeChatPayReadyServicerV2($order['boz_price'], $order_number, '领取面膜费用');
            }else{
                // 调起支付宝支付
                $ali = new Ali(config('ali'));
                $return = $ali->getParam($order['boz_number'], $order['boz_price'], '赠品', '领取面膜费用');
            }

            Db::table('up_bo_orderz')->update($update);

            if($return['status'] == 200){
                Db::commit();
                return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $boz_id, 'price' => $order['boz_price']]);
            }else{
                Db::rollback();
                return json(['status' => 0, 'msg' => $return['message']]);
            }
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新此礼包订单下非本月、未支付的赠品订单为关闭
     * 本月之前下的赠品订单，未支付的不可以再支付
     * @return \think\response\Json
     * bog_id     礼包订单ID
     */
    public function changeOrderStatusToClose(){
        $bog_id = input('bog_id');
        $date = date('Y-m-01 00:00:01');
        $ids = Db::table('up_bo_orderz')
            ->where([
                'boz_user_id' => $this->user_id,
                'boz_order_id' => $bog_id,
                'boz_create_time' => ['<', $date],
                'boz_is_pay' => 1,
                'boz_status' => 1
            ])
            ->column('boz_id');
        if($ids){
            $res = Db::table('up_bo_orderz')->where('boz_id', 'IN', $ids)->update(['boz_status' => 6, 'boz_close_time' => $this->create_time]);
            if($res){
                return json(['status' => 200, 'msg' => true]);
            }else{
                return json(['status' => 0, 'msg' => false]);
            }
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
    }
    
    /**
     * 赠品订单列表
     * @return \think\response\Json
     * bog_id     礼包订单ID
     * boz_status    赠品礼包状态   0 全部   1 待支付   2 待发货   3 待收货   4 已完成
     * page        页码
     */
    public function zengOrderList(){
        $bog_id = input('bog_id');
        $boz_status = input('boz_status'); // 0 全部  1 待支付  2 待发货  3 待收货  4 已完成
        
        $where['boz_order_id'] = $bog_id;
        if($boz_status != 0){
            $where['boz_status'] = $boz_status;
        }
        
        $list = Db::table('up_bo_orderz')
            ->where($where)
            ->field('boz_id, boz_number, boz_status, boz_price, boz_get_month')
            ->order('boz_create_time desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
        
    }
    
    /**
     * 赠品订单物流展示
     * @return \think\response\Json
     * boz_id     赠品订单ID
     */
    public function showZengWuLiu(){
        $boz_id = input('boz_id');
        // 订单
        $order = Db::table('up_bo_orderz')
            ->join('up_user_address', 'addr_id = boz_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('boz_express_company, boz_express_code, boz_addr_id, boz_number, boz_create_time, 
            boz_pay_time, concat(u1.district, u2.district, u3.district, addr_address) address,  
            addr_user_name, addr_user_phone')
            ->where('boz_id', $boz_id)
            ->find();
    
        //*********** 获取快递公司编码
        $code = $order['boz_express_code'];
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
        
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'order' => $order/*, 'address' => $address*/]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'order' => $order/*, 'address' => $address*/]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'order' => $order/*, 'address' => $address*/]);
            }
        }
    }
    
    /**
     * 确认赠品订单收货
     * @return \think\response\Json
     * boz_id      赠品订单ID
     */
    public function confirmZengOrder(){
        $boz_id = input('boz_id');
        
        $order = Db::table('up_bo_orderz')->where('boz_id', $boz_id)->field('boz_status')->find();
        if($order['boz_status'] != 3) return json(['status' => 0, 'msg' => '订单状态异常']);
        
        $res = Db::table('up_bo_orderz')
            ->update([
                'boz_id' => $boz_id,
                'boz_status' => 4,
                'boz_over_time' => $this->create_time
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    //**************************************************   赠品相关    end  *********************************//
    
    //***************************************************  我的脖脸皮团队--首页
    /**
     * 我的脖脸皮团队--首页
     * @return \think\response\Json
     */
    public function myBoTeamList(){
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_invite')->find();
        if($user['user_invite']){
            $teamList = $this->myTeam(1, $user['user_invite']);
        }else{
            $teamList = [];
        }
        if($teamList){
            return json(['status' => 200, 'msg' => $teamList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 我的脖脸皮团队---我的下级用户信息
     * @return \think\response\Json
     * other_user_id     下级用户ID
     */
    public function otherUserFy(){
        $other_user_id = input('other_user_id');
        $other_user = Db::table('up_u_user')
            ->field('user_id, user_image, user_real_name, user_phone')
            ->where('user_id', $other_user_id)
            ->find();
        // 为我带来的总分佣
        $total = Db::table('up_bo_fy')
            ->where('binte_other_user_id', $other_user_id)
            ->where('binte_user_id', $this->user_id)
            ->where('binte_type', 1)
            ->sum('binte_price');
        $other_user['get_total_balance'] = $total;
        return json(['status' => 200, 'msg' => $other_user]);
    }

    //*************************************************  2022/12月修改逻辑    start   **************************************//
    /**
     * 我的脖脸皮
     * @return \think\response\Json
     */
    public function boHome(){
        $field = 'user_username, user_image, user_bo_role, user_bo_balance, user_giftbag_balance, user_role, user_giftbag_role';
        $user = $this->userInfo($this->user_id, $field);
        // 产品订单数量
        $unPay = $this->goodsOrder(1, 1); // 待付款
        $unSend = $this->goodsOrder(1, 2); // 待发货
        $unReceive = $this->goodsOrder(1, 3); // 待收货
        $over = $this->goodsOrder(1, 4); // 已完成
        $user['unPay'] = $unPay;
        $user['unSend'] = $unSend;
        $user['unReceive'] = $unReceive;
        $user['over'] = $over;

        return json(['status' => 200, 'msg' => $user]);
    }

    /**
     * 我的礼包团队---下级
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myGiftbagUser(){
        $user = $this->myGiftbagTeam();
        if($user){
            // 保护日期
            $privateDays = Db::table('up_bo_fy_config')->where('bfc_id', 40)->value('bfc_content');
            foreach ($user as $k => $v){
                $halfYear = date('Y-m-d', strtotime("+{$privateDays} days", strtotime($v['user_giftbag_date'])));
                $user[$k]['indate'] = $halfYear;
            }

            // 礼包数
            $ids = array_column($user, 'user_id');
            $giftbag_order = $this->giftbagList(2, $ids);
            foreach ($user as $k => $v){
                $residue = 0;
                if($giftbag_order){
                    foreach ($giftbag_order as $ke => $vo){
                        if($v['user_id'] == $vo['bog_user_id']){
                            $residue += $vo['bog_zeng_number'];
                        }
                    }
                }
                $user[$k]['residue'] = $residue;
            }
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 我的店铺会员
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myStoreVip(){
        $myStore = Db::table('up_bo_giftbag_store')->where('bs_user_id', $this->user_id)->field('bs_id, bs_status')->find();
        if(!$myStore){
            return json(['status' => 0, 'msg' => '请先申请开通店铺']);
        }else{
            if($myStore['bs_status'] == 1){
                return json(['status' => 0, 'msg' => '您的店铺正在审核中']);
            }elseif ($myStore['bs_status'] == 3){
                return json(['status' => 0, 'msg' => '您的店铺审核未通过，请重新申请']);
            }
        }
        $users = Db::table('up_u_user')
            ->where('user_giftbag_store_id', $myStore['bs_id'])
            ->field('user_id, user_username, user_image, user_phone, user_real_name, user_zeng_get_type')
            ->select();

        if($users){
            $ids = array_column($users, 'user_id');
            $giftbag_order = $this->giftbagList(2, $ids);
            foreach ($users as $k => $v){
                $residue = 0;
                if($giftbag_order){
                    foreach ($giftbag_order as $ke => $vo){
                        if($v['user_id'] == $vo['bog_user_id']){
                            $residue += $vo['bog_zeng_number'];
                        }
                    }
                }
                $users[$k]['residue'] = $residue;
            }
        }else{
            $users = [];
        }

        return json(['status' => 200, 'msg' => $users]);
    }

    /**
     * 我的会员礼包列表
     * vip_user_id      店铺用户ID
     * @return \think\response\Json
     */
    public function giftbagListToGetZeng(){
        $vip_user_id = input('vip_user_id');
        $list = $this->giftBagOrder(2, 1, 0, $vip_user_id);
        if($list){
            foreach($list as $k => $v){
                if($v['gift_images']){
                    $list[$k]['gift_images'] = explode(',', $v['gift_images']);
                }else{
                    $list[$k]['gift_images'] = [];
                }
            }

            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 赠品领取页面展示
     * bog_id    礼包订单ID
     * @return \think\response\Json
     */
    public function showZeng(){
        $bog_id = input('bog_id');
        $data = [];
        // 快递公司
        $data['company'] = $this->expressCompany();
        // 面膜单价
        $data['price'] = $this->getConfig(1);
        // 剩余可领数量
        $data['zeng_number'] = Db::table('up_bo_orderg')->where('bog_id', $bog_id)->value('bog_zeng_number');
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 提交赠品订单---会员礼包列表领取
     * @return \think\response\Json
     * bog_id        礼包订单ID
     * addr_id       收货地址ID
     * order_remark  订单备注
     * order_no      订单数量
     * pay_type      支付方式   1 积分   2 微信   3 支付宝
     * get_type      1 店铺    2 下级
     */
    public function commitZengOrder(){
        $bog_id = input('bog_id');
        $addr_id = input('addr_id');
        $order_remark = input('order_remark');
        $pay_type = input('pay_type');
        $order_no = input('order_no');
        $get_type = input('get_type');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);
        // 单价
        $price = $this->getConfig(1);

        // 判断是否可以领取
        $can = $this->canGetZeng($bog_id, $get_type);
        if($can['status'] != 200) return json($can);

        $giftOrder = Db::table('up_bo_orderg')
            ->where('bog_id', $bog_id)
            ->field('bog_gift_id, bog_zeng_number')
            ->find();

        if($order_no > $giftOrder['bog_zeng_number']){
            return json(['status' => 0, 'msg' => '可领取数量不足']);
        }

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        $order_number = 'BZ_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($order_no == 11){
            $freight = 0;
        }else{
            $freight = 15;
        }
        $total_price = $price * $order_no + $freight;
        $insert = [
            'boz_number' => $order_number,
            'boz_no' => $order_no,
            'boz_pay_type' => $pay_type,
            'boz_user_id' => $this->user_id,
            'boz_order_id' => $bog_id,
            'boz_gift_id' => $giftOrder['bog_gift_id'],
            'boz_addr_id' => $addr_id,
            'boz_freight' => $freight,
            'boz_price' => $total_price,
            'boz_remark' => $order_remark,
//            'boz_get_month' => date('Y-m'),
            'boz_create_time' => $this->create_time,
            'boz_get_type' => $get_type
        ];



        Db::startTrans();
        try{
            // 减剩余可领取数量
//            Db::table('up_bo_orderg')
//                ->where('bog_id', $bog_id)
//                ->update(['bog_zeng_number' => $giftOrder['bog_zeng_number'] - $order_no]);

            $boz_id = Db::table('up_bo_orderz')->insertGetId($insert);

            if($pay_type == 2){
                $wxConfig = config('wechat_servicer');
                $wxConfig['sub_mchid'] = $mchid['mch_code'];
                // 调起微信支付
                $wx = new Wxservicer($wxConfig);
                $return = $wx->WeChatPayReadyServicerV2($total_price, $order_number, '领取面膜费用');
            }else{
                // 调起支付宝支付
                $ali = new Ali(config('ali'));
                $return = $ali->getParam($order_number, $total_price, '赠品', '领取面膜费用');
            }
            if($return['status'] == 200){
                Db::commit();
                return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $boz_id, 'price' => $total_price]);
            }else{
                Db::rollback();
                return json(['status' => 0, 'msg' => $return['message']]);
            }
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 赠品订单详情
     * @return \think\response\Json
     * boz_id      赠品订单ID
     */
    public function zengOrderDetail(){
        $boz_id = input('boz_id');

        $detail = Db::table('up_bo_orderz')
            ->join('up_user_address', 'boz_addr_id = addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->where('boz_id', $boz_id)
            ->field('boz_id, boz_number, boz_status, boz_price, boz_remark, boz_express_company, 
            boz_express_code, boz_create_time, boz_pay_time, boz_send_time, boz_over_time, 
            concat(u1.district, u2.district, u3.district, addr_address) address, 
            addr_user_name, addr_user_phone, boz_no, boz_freight')
            ->find();
        return json(['status' => 200, 'msg' => $detail]);
    }

    /**
     * 礼包订单详情
     * @return \think\response\Json
     * bog_id      礼包订单ID
     */
    public function giftbagOrderDetail(){
        $bog_id = input('bog_id');

        $detail = Db::table('up_bo_orderg')
            ->join('up_user_address', 'addr_id = bog_addr_id', 'LEFT')
            ->join('up_area u1', 'addr_sheng = u1.district_id', 'LEFT')
            ->join('up_area u2', 'addr_shi = u2.district_id', 'LEFT')
            ->join('up_area u3', 'addr_qu = u3.district_id', 'LEFT')
            ->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
            ->where('bog_id', $bog_id)
            ->field('bog_id, bog_number, bog_total_price, bog_status, bog_remark, bog_create_time, 
            bog_pay_time, bog_send_time, bog_over_time, bog_close_time, bog_cancel_time, bog_cancel_reason, 
            bog_express_company, bog_express_code, gift_name, gift_thumb, gift_price, gift_id, 
            concat(u1.district, u2.district, u3.district, addr_address) address, addr_user_name, 
            addr_user_phone, bog_aftersale_status, bog_aftersale_refuse_reason, bog_return_total_price, 
            bog_pay_type, bog_dec_price, bog_get_way')
            ->find();
        if($detail){
            return json(['status' => 200, 'msg' => $detail]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }



    //*************************************************  2022/12月修改逻辑    end   **************************************//


    //******************************  公共方法
    /**
     * 我的礼包
     * @param $use_type     1 用于统计礼包个数    2 用于列表
     * @param $use_range     1 赠品领取页面    2 礼包订单列表页面
     * @param $use_status     订单状态  0 全部  1 待支付  2 待发货  3 已发货  4 已完成
     * @return false|int|\PDOStatement|string|\think\Collection
     */
    private function giftBagOrder($use_type, $use_range, $order_status = 0, $userid){
        $where['bog_user_id'] = $userid;
        if($use_range == 1){
            $where['bog_is_pay'] = 2;
        }else{
            if($order_status != 0){
                $where['bog_status'] = $order_status;
            }
        }
        $query = Db::table('up_bo_orderg')->where($where);
        if($use_type == 1){
            $data = $query->count();
        }else{
            $data = $query
                ->join('up_bo_giftbag', 'bog_gift_id = gift_id', 'LEFT')
                ->field('bog_id, gift_name, gift_images, gift_indate, gift_id, bog_pay_month, 
                bog_indate, gift_thumb, bog_number, bog_total_price, gift_price, bog_status, 
                bog_cancel_reason, bog_indate_month, bog_aftersale_status, bog_zeng_number, bog_number')
                ->order('bog_create_time desc')
                ->page($this->page, 10)
                ->select();
        }
        return $data;
    }
    
    /**
     * 我的产品订单
     * @param $useType    1 统计数量    2 列表
     * @param int $orderStatus    0 全部  1 待付款   2 待发货   3 待收货   4 已完成
     * @return false|int|\PDOStatement|string|\think\Collection
     */
    private function goodsOrder($useType, $orderStatus = 0){
        $where['bo_user_id'] = $this->user_id;
        if($orderStatus != 0) $where['bo_status'] = $orderStatus;
        
        $query = Db::table('up_bo_order')->where($where);
        if($useType == 1){
            $data = $query->count();
        }else{
            $data = $query
                ->field('bo_id, bo_number, bo_is_pay, bo_total_price, bo_status, bo_addr_id, bo_cancel_reason')
                ->order('bo_create_time desc')
                ->page($this->page, 10)
                ->select();
        }
        return $data;
    }
    
    /**
     * 脖脸皮商品订单下商品列表
     * @param $order_id      订单ID
     * @return false|\PDOStatement|string|\think\Collection
     */
    private function orderGoodsList($order_id){
        $goods = Db::table('up_bo_order_info')
            ->join('up_bo_goods', 'bg_id = boi_goods_id', 'LEFT')
            ->where('boi_order_id', $order_id)
            ->field('bg_id, bg_name, bg_thumb, bg_spec, bg_price, boi_goods_number, bg_stock, 
            bg_sale_number, boi_goods_id')
            ->select();
        return $goods;
    }
    
    /**
     * 判断用户是否可以领取赠品
     * 1.没有领取权益不可领    2.购买礼包当月不可领  3.当月领过不可领    4.剩余领取数量为0不可领   5.礼包过期不可领
     * @param $bog_id      礼包订单ID
     * @return array    status 200->可以正常领取，0->不可以领取，1->已领取，但未支付，跳转到支付
     */
    private function canGetZeng($bog_id, $get_type){
        $can = ['status' => 200, 'msg' => '可以正常领取']; // 可以领取

        // 用户是否有领取赠品权益
        // 如果是从店铺领取的
        if($get_type == 1){
            $store = Db::table('up_bo_giftbag_store')->where('bs_user_id', $this->user_id)->field('bs_status, bs_id')->find();
            if(!$store){
                $can = ['status' => 0, 'msg' => '请先申请开通店铺'];
                return $can;
            }else{
                if($store['bs_status'] != 2){
                    $can = ['status' => 0, 'msg' => '您的店铺正在审核中'];
                    return $can;
                }
            }
        }

        // 该订单是否在有效期内
        $gift_order = Db::table('up_bo_orderg')
            ->where('bog_id',  $bog_id)
            ->field('bog_indate, bog_is_pay, bog_status, bog_aftersale_status, bog_zeng_number, bog_pay_time, bog_user_id')->find();
//        $pay_month = date('Y-m', strtotime($gift_order['bog_pay_time']));
//        if(strtotime($month) == strtotime($pay_month)){
//            $can = ['status' => 0, 'msg' => '购买礼包当月，不可领取'];
//            return $can;
//        }
        if($gift_order['bog_is_pay'] == 1){
            $can = ['status' => 0, 'msg' => '该礼包订单尚未付款'];
            return $can;
        }else{
            if($gift_order['bog_status'] == 5 || $gift_order['bog_status'] == 6){
                $can = ['status' => 0, 'msg' => '礼包订单已取消或已关闭'];
                return $can;
            }
        }

        // 领取渠道
        $user = Db::table('up_u_user')->where('user_id', $gift_order['bog_user_id'])->field('user_giftbag_store_id, user_zeng_get_type')->find();
        if($user['user_zeng_get_type'] == 0){
//            if($user['user_giftbag_store_id'] != $store['bs_id']){
//                $can = ['status' => 0, 'msg' => '该礼包的购买者还不是您的会员'];
//                return $can;
//            }
        }else{
            if($get_type != $user['user_zeng_get_type']){
                $can = ['status' => 0, 'msg' => '该用户的面膜已在其它渠道领取'];
            }
        }

        $month = date('Y-m');
        /**
         * 由于领取面膜的逻辑变更为购买当月或者加入会员不领，不扣剩余月数和面膜数量，所以会导致用户在礼包面膜
         * 有效期之后，还会有剩余月数和面膜，所以这里暂时将过期的判断改掉，用0来判断 2023.04.14
         */
//        if(strtotime($month) > strtotime($gift_order['bog_indate'])){
        if(0){
            $can = ['status' => 0, 'msg' => '该礼包已过期，无法领取'];
            return $can;
        } else{
            if($gift_order['bog_zeng_number'] == 0){
                $can = ['status' => 0, 'msg' => '可领取数量为0'];
                return $can;
            }
//            $alreadyGet = Db::table('up_bo_orderz')
//                ->where(['boz_user_id' => $this->user_id, 'boz_order_id' => $bog_id, 'boz_get_month' => $month])
//                ->field('boz_status, boz_id')
//                ->find();
//            if($alreadyGet){
//                $can = ['status' => 0, 'msg' => '当月已领取过该赠品'];
////                if($alreadyGet['boz_status'] == 1){
////                    $can = ['status' => 1, 'msg' => '有未支付订单，跳转到订单支付', 'boz_id' => $alreadyGet['boz_id']];
////                }
//                return $can;
//            }
        }
        return $can;
    }
    
    /**
     * 默认快递公司
     * @return mixed
     */
    private function expressCompany(){
        return Db::table('up_about')->where('id', 7)->value('content');
    }
    
    /**
     * 运费&分佣
     * @return mixed
     */
    private function getConfig($bfc_id){
        $freight = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
        return $freight;
    }
    
    /**
     * 用户信息
     * @return array|false|\PDOStatement|string|\think\Model
     */
    private function userInfo($user_id, $field){
        $user = Db::table('up_u_user')->where('user_id', $user_id)->field($field)->find();
        return $user;
    }
    
    /**
     * 我的脖脸皮团队
     * @param int $type    1 列表    2 统计总积分
     * @param $my_invite   我的邀请码
     * @return false|float|int|\PDOStatement|string|\think\Collection
     */
    private function myTeam($type = 1, $my_invite){
        $query = Db::table('up_u_user')->where('user_bo_invite_other', $my_invite)->where('user_status', 1);
        if($type == 1){ // 我的团队列表
            $data = $query->field('user_id, user_real_name')
                ->order('user_time desc')
//                ->page($this->page, 10)
                ->select();
        }else{ // 我的团队总计
            $data = $query->sum('user_bo_total_balance');
        }
        return $data;
    }

    /**
     * 本月获得的佣金
     * @return float|int
     */
    private function thisMonthFy(){
        // 本月第一天
        $first_day = date('Y-m-01 00:00:00');
        // 当前时间
        $now = date('Y-m-d H:i:s');
        // 当月的分佣
        $untixian = Db::table('up_bo_fy')
            ->where([
                'binte_user_id' => $this->user_id,
                'binte_type' => 1,
                'binte_cate' => 1,
                'binte_time' => ['between', [$first_day, $now]]
            ])
            ->sum('binte_price');
        return $untixian;
    }

    /**
     * 我的礼包团队----展示我的礼包下级
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function myGiftbagTeam(){
        $myInvite = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_invite');
        $team = Db::table('up_u_user')
            ->where([
                'user_giftbag_invite_other' => $myInvite,
                'user_status' => 1
            ])
            ->field('user_id, user_username, user_image, user_phone, user_giftbag_date, 
            user_real_name, user_zeng_get_type')
            ->select();
        return $team;
    }

    /**
     * 我的店铺会员礼包
     * @param $type      1 店铺中某个用户的礼包列表    2 我的店铺列表某个用户所有礼包数量
     * @param $uid       用户ID/团队用户ID
     * @return bool|int|\PDOStatement|string|\think\Collection
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function giftbagList($type, $uid){
        $where['bog_is_pay'] = 2;
        if($type == 1){ // 查询某个用户
            $where['bog_user_id'] = $uid;
        }else{ // 查询我的店铺用户
            $uid_arr = implode($uid, ',');
            $where['bog_user_id'] = ['IN', $uid_arr];
        }

        $query = Db::table('up_bo_orderg')->where($where);
        if($type == 1){
            $data = $query->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
                ->field('gift_id, gift_name, gift_thumb, bog_pay_month, bog_indate, bog_indate_month, bog_zeng_number')
                ->page($this->page, 10)
                ->order('bog_create_time desc')
                ->select();
        }else{
            $data = $query->field('bog_zeng_number, bog_user_id')->select();
        }
        return $data;
    }
}